{% extends 'assets/base.html' %}
{% load static %}

{% block title %}AI智能化仪表板{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
<style>
.ai-card {
    border-left: 4px solid #007bff;
    transition: all 0.3s ease;
}
.ai-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.recommendation-item {
    border-left: 3px solid #28a745;
    padding: 15px;
    margin-bottom: 10px;
    background: #f8f9fa;
    border-radius: 0 5px 5px 0;
}
.recommendation-item.priority-high {
    border-left-color: #dc3545;
}
.recommendation-item.priority-urgent {
    border-left-color: #fd7e14;
}
.anomaly-item {
    border-left: 3px solid #ffc107;
    padding: 15px;
    margin-bottom: 10px;
    background: #f8f9fa;
    border-radius: 0 5px 5px 0;
}
.anomaly-item.severity-high {
    border-left-color: #dc3545;
}
.anomaly-item.severity-critical {
    border-left-color: #6f42c1;
}
.confidence-badge {
    font-size: 0.8em;
    padding: 2px 6px;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
            <li class="breadcrumb-item active" aria-current="page">AI智能化</li>
        </ol>
    </nav>

    <!-- 页面标题和操作按钮 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <h2 class="mb-0">
                    <i class="fas fa-brain me-2 text-primary"></i>AI智能化仪表板
                </h2>
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" onclick="generateRecommendations()" title="基于当前数据生成智能推荐">
                        <i class="fas fa-magic me-1"></i>生成推荐
                    </button>
                    <button type="button" class="btn btn-warning" onclick="runAnomalyDetection()" title="运行异常检测分析">
                        <i class="fas fa-search me-1"></i>异常检测
                    </button>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" title="更多AI功能">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="{% url 'assets:ai_recommendations_list' %}">
                                <i class="fas fa-lightbulb me-2"></i>推荐历史
                            </a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:ai_anomaly_detection_list' %}">
                                <i class="fas fa-exclamation-triangle me-2"></i>异常历史
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="exportAIReport()">
                                <i class="fas fa-download me-2"></i>导出AI报告
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="showAISettings()">
                                <i class="fas fa-cog me-2"></i>AI设置
                            </a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card ai-card">
                <div class="card-body text-center">
                    <i class="fas fa-lightbulb fa-2x text-primary mb-2"></i>
                    <h4>{{ stats.total_recommendations }}</h4>
                    <p class="text-muted">总推荐数</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card ai-card">
                <div class="card-body text-center">
                    <i class="fas fa-envelope fa-2x text-success mb-2"></i>
                    <h4>{{ stats.unread_recommendations }}</h4>
                    <p class="text-muted">未读推荐</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card ai-card">
                <div class="card-body text-center">
                    <i class="fas fa-exclamation-triangle fa-2x text-warning mb-2"></i>
                    <h4>{{ stats.active_anomalies }}</h4>
                    <p class="text-muted">活跃异常</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card ai-card">
                <div class="card-body text-center">
                    <i class="fas fa-check-circle fa-2x text-info mb-2"></i>
                    <h4>{{ stats.resolved_anomalies }}</h4>
                    <p class="text-muted">已解决异常</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 最新推荐 -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5><i class="fas fa-lightbulb"></i> 最新推荐</h5>
                    <a href="{% url 'assets:ai_recommendations_list' %}" class="btn btn-sm btn-outline-primary">
                        查看全部
                    </a>
                </div>
                <div class="card-body">
                    {% if recommendations %}
                        {% for rec in recommendations %}
                        <div class="recommendation-item priority-{{ rec.priority }}" data-id="{{ rec.id }}">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">{{ rec.title }}</h6>
                                    <p class="mb-2 text-muted small">{{ rec.description|truncatechars:100 }}</p>
                                    <div class="d-flex align-items-center">
                                        <span class="badge bg-{{ rec.priority }} me-2">{{ rec.get_priority_display }}</span>
                                        <span class="badge bg-secondary confidence-badge me-2">
                                            置信度: {{ rec.confidence_score|floatformat:1 }}
                                        </span>
                                        <small class="text-muted">{{ rec.created_at|date:"m-d H:i" }}</small>
                                    </div>
                                </div>
                                <div class="btn-group-vertical btn-group-sm">
                                    <button class="btn btn-success btn-sm" onclick="handleRecommendation({{ rec.id }}, 'accept')">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn btn-secondary btn-sm" onclick="handleRecommendation({{ rec.id }}, 'dismiss')">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-lightbulb fa-3x mb-3"></i>
                            <p>暂无推荐数据</p>
                            <button class="btn btn-primary" onclick="generateRecommendations()">
                                生成推荐
                            </button>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- 异常检测 -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5><i class="fas fa-exclamation-triangle"></i> 异常检测</h5>
                    <a href="{% url 'assets:ai_anomaly_detection_list' %}" class="btn btn-sm btn-outline-warning">
                        查看全部
                    </a>
                </div>
                <div class="card-body">
                    {% if anomalies %}
                        {% for anomaly in anomalies %}
                        <div class="anomaly-item severity-{{ anomaly.severity }}" data-id="{{ anomaly.id }}">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">{{ anomaly.asset.name }}</h6>
                                    <p class="mb-2 text-muted small">{{ anomaly.description|truncatechars:100 }}</p>
                                    <div class="d-flex align-items-center">
                                        <span class="badge bg-{{ anomaly.severity }} me-2">{{ anomaly.get_severity_display }}</span>
                                        <span class="badge bg-info me-2">{{ anomaly.get_anomaly_type_display }}</span>
                                        <small class="text-muted">{{ anomaly.detected_at|date:"m-d H:i" }}</small>
                                    </div>
                                </div>
                                <div class="btn-group-vertical btn-group-sm">
                                    {% if not anomaly.is_confirmed %}
                                    <button class="btn btn-warning btn-sm" onclick="handleAnomaly({{ anomaly.id }}, 'confirm')">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    {% endif %}
                                    {% if anomaly.is_confirmed and not anomaly.is_resolved %}
                                    <button class="btn btn-success btn-sm" onclick="handleAnomaly({{ anomaly.id }}, 'resolve')">
                                        <i class="fas fa-check-double"></i>
                                    </button>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-shield-alt fa-3x mb-3"></i>
                            <p>暂无异常检测数据</p>
                            <button class="btn btn-warning" onclick="runAnomalyDetection()">
                                运行检测
                            </button>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 推荐类型分布图表 -->
    {% if recommendation_types %}
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-chart-pie"></i> 推荐类型分布</h5>
                </div>
                <div class="card-body">
                    <canvas id="recommendationChart" height="100"></canvas>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- 处理推荐模态框 -->
<div class="modal fade" id="recommendationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">处理推荐</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="recommendationText"></p>
                <div class="form-group">
                    <label>备注</label>
                    <textarea class="form-control" id="recommendationNotes" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" id="acceptRecommendation">接受</button>
                <button type="button" class="btn btn-danger" id="dismissRecommendation">忽略</button>
            </div>
        </div>
    </div>
</div>

<!-- 处理异常模态框 -->
<div class="modal fade" id="anomalyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">处理异常</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="anomalyText"></p>
                <div class="form-group">
                    <label>处理备注</label>
                    <textarea class="form-control" id="anomalyNotes" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-warning" id="confirmAnomaly">确认异常</button>
                <button type="button" class="btn btn-success" id="resolveAnomaly">解决异常</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
// 全局变量
let currentRecommendationId = null;
let currentAnomalyId = null;

// 生成推荐
function generateRecommendations() {
    showLoading('正在生成推荐...');
    
    fetch('{% url "assets:ai_generate_recommendations" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            type: 'all'
        })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            showAlert('success', data.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '生成推荐失败: ' + error.message);
    });
}

// 运行异常检测
function runAnomalyDetection() {
    showLoading('正在运行异常检测...');
    
    fetch('{% url "assets:ai_run_anomaly_detection" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            type: 'all'
        })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            showAlert('success', data.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '异常检测失败: ' + error.message);
    });
}

// 处理推荐
function handleRecommendation(id, action) {
    fetch(`/assets/ai/recommendations/${id}/handle/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            action: action
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            // 移除处理过的推荐项
            const item = document.querySelector(`[data-id="${id}"]`);
            if (item) {
                item.style.opacity = '0.5';
                setTimeout(() => item.remove(), 1000);
            }
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        showAlert('error', '处理推荐失败: ' + error.message);
    });
}

// 处理异常
function handleAnomaly(id, action) {
    fetch(`/assets/ai/anomalies/${id}/handle/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            action: action
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            // 更新异常项状态
            const item = document.querySelector(`[data-id="${id}"]`);
            if (item && action === 'resolve') {
                item.style.opacity = '0.5';
                setTimeout(() => item.remove(), 1000);
            }
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        showAlert('error', '处理异常失败: ' + error.message);
    });
}

// 推荐类型分布图表
{% if recommendation_types %}
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('recommendationChart').getContext('2d');
    
    const labels = [];
    const data = [];
    const colors = ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1'];
    
    {% for item in recommendation_types %}
    labels.push('{{ item.recommendation_type }}');
    data.push({{ item.count }});
    {% endfor %}
    
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: colors.slice(0, data.length),
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
});
{% endif %}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showLoading(message) {
    // 显示加载提示
    const loading = document.createElement('div');
    loading.id = 'loading-overlay';
    loading.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center';
    loading.style.backgroundColor = 'rgba(0,0,0,0.5)';
    loading.style.zIndex = '9999';
    loading.innerHTML = `
        <div class="bg-white p-4 rounded text-center">
            <div class="spinner-border text-primary mb-2"></div>
            <div>${message}</div>
        </div>
    `;
    document.body.appendChild(loading);
}

function hideLoading() {
    const loading = document.getElementById('loading-overlay');
    if (loading) {
        loading.remove();
    }
}

function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alert.style.top = '20px';
    alert.style.right = '20px';
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    // 自动移除
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}
</script>
{% endblock %}